﻿using Newtonsoft.Json;

namespace Common {
	public sealed class JsonFile<T> where T : new() {
		public JsonFile(string path, bool formatted = true) {
			FilePath = path;
			Formatted = formatted;
			Load();
		}

		static string Serialize(T source, bool formatted) {
			return JsonConvert.SerializeObject(source, (formatted ? Formatting.Indented : Formatting.None));
		}

		static T Deserialize(string json){
			return JsonConvert.DeserializeObject<T>(json);
		}
		public void Load() {
			if (!File.IsExists(FilePath)) {
				Source = new T();
				return;
			}
			File file=File.Open(FilePath,File.OpenMode.Read);
			string text = file.GetAllText();
			file.Close();
			Source = Deserialize(text);
		}
		public void Save() {
			File file = File.Open(FilePath, File.OpenMode.TruncateWrite);
			file.WriteText(Serialize(Source,Formatted));
			file.Close();
		}

		public string FilePath { get; }
		public bool Formatted { get; set; }
		public T Source { get; set; }
	}
}